#define _GNU_SOURCE

#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

pthread_spinlock_t mySpinlock;

/* Return the UNIX time in microseconds */
long long ustime(void) {
  struct timeval tv;
  long long ust;

  gettimeofday(&tv, NULL);
  ust = ((long long)tv.tv_sec) * 1000000;
  ust += tv.tv_usec;
  return ust;
}

void loopfunc() {
  int c;
  for (int i = 0; i < 1024; i++) {
    c++;
    void *buff = malloc(1024);
    memset(buff, 2, 1024);
    free(buff);
  }
  printf("%d\n", c);
}

void *spinlockTest(void *arg) {
  while (1) {
    pthread_spin_lock(&mySpinlock);
    loopfunc();
    pthread_spin_unlock(&mySpinlock);
  }
  return NULL;
}

int main(int argc, char *argv[]) {
  pid_t pid = getpid();
  printf("pid=%d\n", pid);

  int cpuid = 0;
  pthread_spin_init(&mySpinlock, 0);

  for (int i = 0; i < 128; i++) {
    pthread_t thread;
    int err = pthread_create(&thread, NULL, spinlockTest, NULL);
    if (err != 0) {
      printf("spinlockTest线程创建失败\n");
    }
  }
  printf("sleep for 600s\n");
  sleep(600);

  return 0;
}